﻿using RXY_Mall.Application.Order.Dto;
using RXY_Mall.Core;
using RXY_Mall.Core.Tool;
using RXY_Mall.Data;
using RXY_Mall.Domain;
using Newtonsoft.Json;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RXY_Mall.Application.Order
{
    public class OrderService : IOrderService
    {
        RXY_MallContext db = new RXY_MallContext();

        #region 订单列表
        /// <summary>
        /// 获得订单信息
        /// </summary>
        /// <param name="user_id">用户ID</param>
        /// <returns></returns>
        public async Task<Response<GetOrderInfoOutput>> GetOrderInfo(int shop_id)
        {
            Response<GetOrderInfoOutput> result = new Response<GetOrderInfoOutput>();
            result.code = 0;
            result.msg = "";
            try
            {
                List<int> lstStatus = new List<int>();
                lstStatus.Add((int)OrderStatus.Shipment);
                lstStatus.Add((int)OrderStatus.Receive);
                //lstStatus.Add((int)OrderStatus.Comment);
                lstStatus.Add((int)OrderStatus.Complete);

                var source = db.gw_orders
                    .Include(o => o.gw_order_goods)
                    .Where(o => o.gw_order_goods.FirstOrDefault().goods_type != (int)GoodsType.Free && o.gw_order_goods.FirstOrDefault().buy_type == (int)BuyType.DirectBuy || (o.gw_order_goods.FirstOrDefault().buy_type == (int)BuyType.GroupBuy && lstStatus.Contains(o.status)));
                if (shop_id != 0)
                {
                    source = source.Where(s => s.gw_order_goods.FirstOrDefault().shop_id == shop_id);
                }

                //var date = DateTime.Now.AddMonths(-1);
                var orderStatus = await source
                    .GroupBy(o => new { o.status, o.gw_order_goods.FirstOrDefault().goods_type })
                    .Select(o => new
                    {
                        status = o.Key.status,
                        goods_type = o.Key.goods_type,
                        count = o.Count()
                    })
                    .ToListAsync();

                //List<int> lstStatus = new List<int>();
                //lstStatus.Add((int)ReturnStatus.已完成);
                //lstStatus.Add((int)ReturnStatus.已取消);
                //lstStatus.Add((int)ReturnStatus.审核失败);

                //var returnCount = await db.gw_returns.CountAsync(r => r.add_time > date && r.user_id == user_id && !lstStatus.Contains(r.status) && !r.deleted);

                GetOrderInfoOutput output = new GetOrderInfoOutput();
                foreach (var item in orderStatus)
                {
                    var status = (OrderStatus)item.status;
                    switch (status)
                    {
                        case OrderStatus.Pay:
                            output.pay_count += item.count;
                            break;
                        case OrderStatus.Group:
                            if (item.goods_type == (int)GoodsType.Free)
                            {
                                continue;
                            }
                            output.group_count += item.count;
                            break;
                        case OrderStatus.Failure:
                            output.failure_count += item.count;
                            break;
                        case OrderStatus.Shipment:
                            output.shipment_count += item.count;
                            break;
                        case OrderStatus.Receive:
                            output.receive_count += item.count;
                            break;
                        //case OrderStatus.Comment:
                        //    output.comment_count += item.count;
                        //    break;
                        case OrderStatus.Complete:
                            output.complete_count += item.count;
                            break;
                        case OrderStatus.Cancel:
                            output.cancel_count += item.count;
                            break;
                        default:
                            break;
                    }
                }
                //output.ReturnCount = returnCount;

                result.code = 1;
                result.data = output;
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.ToString();
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 获得物流
        /// </summary>
        /// <returns></returns>
        public Response<IList<GetLogisticsOutput>> GetLogistics()
        {
            Response<IList<GetLogisticsOutput>> result = new Response<IList<GetLogisticsOutput>>();
            try
            {
                var source = db.gw_base_logistics.Where(l => l.status == 1).OrderBy(l => l.sort)
                    .Select(item => new GetLogisticsOutput
                    {
                        logistics_id = item.id,
                        logistics_name = item.name,
                        logistics_telephone = item.telephone,
                    }).ToList();

                result.code = 1;
                result.data = source;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.msg = ex.ToString();
                result.code = 2;
            }
            return result;
        }

        /// <summary>
        /// 订单列表
        /// </summary>
        /// <param name="receiver_name"></param>
        /// <param name="receiver_mobile"></param>
        /// <param name="shop_name"></param>
        /// <param name="order_no"></param>
        /// <param name="start_date"></param>
        /// <param name="end_date"></param>
        /// <param name="order_status"></param>
        /// <param name="pay_status"></param>
        /// <param name="shipment_status"></param>
        /// <param name="pay_type"></param>
        /// <param name="user_no"></param>
        /// <param name="page_index"></param>
        /// <param name="page_size"></param>
        /// <param name="shop_id"></param>
        /// <returns></returns>
        public Response<IPagedList<GetOrdersOutput>> GetOrders(string receiver_name, string receiver_mobile, string shop_name, string order_no, string start_date, string end_date, int order_status, int pay_status, int shipment_status, int pay_type, string user_no, int page_index = 1, int page_size = 20, int shop_id = -1)
        {
            Response<IPagedList<GetOrdersOutput>> result = new Response<IPagedList<GetOrdersOutput>>();
            try
            {
                List<int> lstStatus = new List<int>();
                lstStatus.Add((int)OrderStatus.Shipment);
                lstStatus.Add((int)OrderStatus.Receive);
                lstStatus.Add((int)OrderStatus.Complete);

                var source = db.gw_orders
                    .Include(o => o.gw_company)
                    .Include(o => o.gw_shop)
                    .Include(o => o.gw_order_address)
                    .Include(o => o.gw_order_goods)
                    .Where(o => lstStatus.Contains(o.status) && o.company_id != null)
                    .Select(item => new GetOrdersOutput
                    {
                        add_time = item.add_time,
                        user_id = item.user_id,
                        goods_total = item.goods_total,
                        order_no = item.order_no,
                        order_id = item.id,
                        _order_status = item.status,
                        _pay_type = item.pay_type,
                        _shipment_status = item.shipment_status,
                        _pay_status = item.pay_status,
                        receiver_mobile = item.gw_order_address.mobile,
                        receiver_name = item.gw_order_address.accepter_name,
                        shop_name = item.gw_shop.name,
                        company_name = item.gw_company.name,
                        shop_id = item.gw_order_goods.FirstOrDefault().shop_id,
                        shipping_fee = item.shipping_fee,
                        discounts = item.discounts,
                        amount = item.amount,
                        area = item.gw_order_address.area,
                    });

                if (shop_id > -1)
                {
                    source = source.Where(s => s.shop_id == shop_id);
                }
                if (!string.IsNullOrEmpty(order_no))
                {
                    source = source.Where(s => s.order_no == order_no);
                }
                if (!string.IsNullOrEmpty(user_no) && Validator.IsInt(user_no))
                {
                    int userNo = int.Parse(user_no);
                    source = source.Where(s => s.user_id == userNo);
                }
                if (order_status != (int)OrderStatus.All)
                {
                    source = source.Where(s => s._order_status == order_status);
                }
                if (pay_status != (int)PayStatus.All)
                {
                    source = source.Where(s => s._pay_status == pay_status);
                }
                if (shipment_status != (int)ShipmentStatus.All)
                {
                    source = source.Where(s => s._shipment_status == shipment_status);
                }
                if (pay_type != (int)PayType.All)
                {
                    source = source.Where(s => s._pay_type == pay_type);
                }
                if (!string.IsNullOrWhiteSpace(receiver_name))
                {
                    source = source.Where(s => s.receiver_name.Contains(receiver_name));
                }
                if (!string.IsNullOrWhiteSpace(receiver_mobile))
                {
                    source = source.Where(s => s.receiver_mobile.Contains(receiver_mobile));
                }
                if (!string.IsNullOrWhiteSpace(shop_name))
                {
                    source = source.Where(s => s.shop_name.Contains(shop_name));
                }
                if (!string.IsNullOrWhiteSpace(start_date))
                {
                    DateTime start;
                    if (DateTime.TryParse(start_date, out start))
                        source = source.Where(s => s.add_time > start);
                }
                if (!string.IsNullOrWhiteSpace(end_date))
                {
                    DateTime end;
                    if (DateTime.TryParse(end_date, out end))
                        source = source.Where(s => s.add_time <= end);
                }

                source = source.OrderByDescending(s => s.add_time);

                var pagelist = new PagedList<GetOrdersOutput>(source, page_index, page_size);
                foreach (var item in pagelist)
                {
                    switch ((PayType)item._pay_type)
                    {
                        case PayType.Balance:
                            item.pay_type = "余额支付";
                            break;
                        case PayType.WeChatApp:
                            item.pay_type = "微信App支付";
                            break;
                        case PayType.Alipay:
                            item.pay_type = "支付宝支付";
                            break;
                        case PayType.WeChatWeb:
                            item.pay_type = "微信公众号支付";
                            break;
                        case PayType.WeChatH5:
                            item.pay_type = "微信H5支付";
                            break;
                        default:
                            break;
                    }
                    switch ((OrderStatus)item._order_status)
                    {
                        case OrderStatus.Pay:
                            item.order_status = "待付款";
                            break;
                        case OrderStatus.Group:
                            item.order_status = "待分享";
                            break;
                        case OrderStatus.Failure:
                            item.order_status = "拼单失败";
                            break;
                        case OrderStatus.Shipment:
                            item.order_status = "待发货";
                            break;
                        case OrderStatus.Receive:
                            item.order_status = "待收货";
                            break;
                        //case OrderStatus.Comment:
                        //    item.order_status = "待评论";
                        //    break;
                        case OrderStatus.Complete:
                            item.order_status = "完成";
                            break;
                        case OrderStatus.GroupComplete:
                            item.order_status = "拼单完成，但未获得商品";
                            break;
                        case OrderStatus.Cancel:
                            item.order_status = "取消";
                            break;
                        default:
                            break;
                    }
                    switch ((PayStatus)item._pay_status)
                    {
                        //case PayStatus.待处理:
                        //    item.pay_status = "待处理";
                        //    break;
                        case PayStatus.已付款:
                            item.pay_status = "已付款";
                            break;
                        case PayStatus.部分退款:
                            item.pay_status = "部分退款";
                            break;
                        case PayStatus.退款:
                            item.pay_status = "退款";
                            break;
                        default:
                            break;
                    }
                    switch ((ShipmentStatus)item._shipment_status)
                    {
                        case ShipmentStatus.未发货:
                            item.shipment_status = "未发货";
                            break;
                        //case ShipmentStatus.部分配送:
                        //    item.shipment_status = "部分配送";
                        //    break;
                        case ShipmentStatus.已发货:
                            item.shipment_status = "已发货";
                            break;
                            //case ShipmentStatus.已收货:
                            //    item.shipment_status = "已交货";
                            //    break;
                    }

                    //item.goods.specs = JsonConvert.DeserializeObject<List<SpecOutput>>(item.goods.json_specs);
                    //StringBuilder sb = new StringBuilder();
                    //foreach (var sku in item.goods.specs)
                    //{
                    //    sb.Append(sku.spec_key);
                    //    sb.Append(":");
                    //    sb.Append(sku.spec_value);
                    //    sb.Append(";");
                    //}
                    //item.goods.json_specs = sb.ToString();
                }
                result.code = 1;
                result.data = pagelist;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.msg = ex.ToString();
                result.code = 2;
            }
            return result;
        }

        /// <summary>
        /// 修改运单号
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<Response<bool>> UpdateLogistics(UpdateLogisticsInput input)
        {
            var result = new Response<bool>();
            try
            {
                var order = await db.gw_orders
                    .Include(o => o.gw_order_goods)
                    .Include(o => o.gw_order_waybill)
                    .FirstOrDefaultAsync(o => o.id == input.order_id);

                if (input.shop_id != 0)
                {
                    if (order.gw_order_goods.FirstOrDefault().shop_id != input.shop_id)
                    {
                        result.msg = "权限不足";
                        return result;
                    }
                }

                if (order.status != (int)OrderStatus.Shipment)
                {
                    result.msg = "用户取消或已发货";
                    return result;
                }

                if (order.gw_order_waybill != null)
                {
                    order.gw_order_waybill.company_name = input.logistics_name.Split(',')[0];
                    order.gw_order_waybill.telphone = input.logistics_name.Split(',')[1];
                    order.gw_order_waybill.waybill_no = input.waybill_no;
                    db.Entry(order.gw_order_waybill).Property(w => w.company_name).IsModified = true;
                    db.Entry(order.gw_order_waybill).Property(w => w.telphone).IsModified = true;
                    db.Entry(order.gw_order_waybill).Property(w => w.waybill_no).IsModified = true;
                }
                else
                {
                    order.gw_order_waybill = new gw_order_waybill()
                    {
                        company_name = input.logistics_name.Split(',')[0],
                        telphone = input.logistics_name.Split(',')[1],
                        waybill_no = input.waybill_no,
                    };
                    db.gw_order_waybills.Add(order.gw_order_waybill);
                }
                order.status = (int)OrderStatus.Receive;
                order.shipment_status = (int)ShipmentStatus.已发货;
                order.shipment_time = DateTime.Now;

                ////订单结算
                //var gw_shop_finance_settlement = new gw_shop_finance_settlement()
                //{
                //    add_time = DateTime.Now,
                //    account_period = order.gw_order_goods.gw_goods.gw_shop.account_period,
                //    money = 0,
                //    order_id = order.id,
                //    order_no = order.order_no,
                //    order_total = order.goods_total,
                //    goods_type = (byte)order.gw_order_goods.FirstOrDefault().goods_type,
                //    service_rate = order.gw_order_goods.service_rate,
                //    shop_id = order.gw_order_goods.FirstOrDefault().shop_id,
                //    type = 1,
                //    status = 1,
                //    settlement_no = "FS" + DateTime.Now.ToString("yyMMddHHmmss") + RandomHelper.CreateRandomValue(6),
                //};
                //gw_shop_finance_settlement.money = order.gw_order_goods.settlement_price == null ? 0 : (decimal)order.gw_order_goods.settlement_price * order.gw_order_goods.quantity;
                //if (gw_shop_finance_settlement.goods_type == 1 && (order.gw_order_goods.settlement_price == null || order.gw_order_goods.settlement_price <= 0))
                //{
                //    var money = order.gw_order_goods.pay_price * order.gw_order_goods.quantity * (1 - order.gw_order_goods.service_rate / 100);
                //    money = Math.Round(money, 2, MidpointRounding.AwayFromZero);
                //    gw_shop_finance_settlement.money = money;
                //}

                //var money = order.gw_order_goods.pay_price * order.gw_order_goods.quantity * (1 - order.gw_order_goods.service_rate / 100);
                //money = Math.Round(money, 2, MidpointRounding.AwayFromZero);
                //gw_shop_finance_settlement.money = money;
                //if ((gw_shop_finance_settlement.goods_type == 2 || gw_shop_finance_settlement.goods_type == 3) && order.gw_order_goods.settlement_price != null && order.gw_order_goods.settlement_price > 0)
                //{
                //    gw_shop_finance_settlement.money = (decimal)order.gw_order_goods.settlement_price * order.gw_order_goods.quantity;
                //}
                //db.gw_shop_finance_settlements.Add(gw_shop_finance_settlement);

                await db.SaveChangesAsync();
                result.code = 1;
                result.msg = "发货成功";
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.msg = ex.ToString();
                result.code = 2;
            }
            return result;
        }

        //订单详情
        public async Task<Response<GetOrderOutput>> GetOrder(int order_id, int shop_id = 0)
        {
            Response<GetOrderOutput> result = new Response<GetOrderOutput>();
            try
            {
                var order = await db.gw_orders
                    .Include(o => o.gw_order_address)
                    .Include(o => o.gw_order_goods)
                    .Include(o => o.gw_shop)
                    .Where(o => o.id == order_id)
                    .Select(item => new GetOrderOutput()
                    {
                        add_time = item.add_time,
                        group_time = item.group_time,
                        receive_time = item.receive_time,
                        shipment_time = item.shipment_time,
                        cancel_time = item.cancel_time,
                        complete_time = item.complete_time,
                        comment_time = item.comment_time,
                        order_id = item.id,
                        order_no = item.order_no,
                        _order_status = item.status,
                        amount = item.amount,
                        discounts = item.discounts,
                        shipping_fee = item.shipping_fee,
                        _shipment_status = item.shipment_status,

                        _pay_type = item.pay_type,
                        pay_expire_time = item.pay_expire_time,
                        pay_time = item.pay_time,
                        pay_no = item.pay_no,
                        _pay_status = item.pay_status,

                        goods_total = item.goods_total,
                        goods_count = item.goods_count,

                        goods_list = item.gw_order_goods.Select(g => new OrderGoods()
                        {
                            goods_id = g.goods_id,
                            goods_name = g.goods_name,
                            json_specs = g.sku_specs,
                            goods_price = g.pay_price,
                            goods_quantity = g.quantity,
                            picture_url = g.picture_url,
                        }).ToList(),

                        shop = new ShopOutput()
                        {
                            shop_id = (int)item.shop_id,
                            shop_logo = item.gw_shop.logo,
                            shop_name = item.gw_shop.name,
                        },

                        address = new OrderAddress()
                        {
                            address = item.gw_order_address.address,
                            accepter_name = item.gw_order_address.accepter_name,
                            area = item.gw_order_address.area,
                            mobile = item.gw_order_address.mobile,
                        },

                    }).FirstOrDefaultAsync();

                if (order == null)
                {
                    result.msg = "订单不存在";
                    return result;
                }
                if (shop_id != 0)
                {
                    if (shop_id != order.shop.shop_id)
                    {
                        result.code = 4;
                        result.msg = "权限不足";
                        return result;
                    }
                }

                if (order != null)
                {
                    foreach (var goods in order.goods_list)
                    {
                        goods.specs = JsonConvert.DeserializeObject<List<SpecOutput>>(goods.json_specs);
                        StringBuilder sb = new StringBuilder();
                        foreach (var item in goods.specs)
                        {
                            sb.Append(item.spec_key);
                            sb.Append(":");
                            sb.Append(item.spec_value);
                            sb.Append(";");
                        }
                        goods.json_specs = sb.ToString();
                    }

                    if (order.gw_order_waybill != null)
                    {
                        order.waybill = new Waybill()
                        {
                            company_name = order.gw_order_waybill.company_name,
                            telphone = order.gw_order_waybill.telphone,
                            waybill_no = order.gw_order_waybill.waybill_no,
                        };
                    }

                    switch ((PayType)order._pay_type)
                    {
                        case PayType.Balance:
                            order.pay_type = "余额支付";
                            break;
                        case PayType.WeChatApp:
                            order.pay_type = "微信App支付";
                            break;
                        case PayType.Alipay:
                            order.pay_type = "支付宝支付";
                            break;
                        case PayType.WeChatWeb:
                            order.pay_type = "微信公众号支付";
                            break;
                        case PayType.WeChatH5:
                            order.pay_type = "微信H5支付";
                            break;
                        default:
                            break;
                    }
                    switch ((OrderStatus)order._order_status)
                    {
                        case OrderStatus.Pay:
                            order.order_status = "待付款";
                            break;
                        case OrderStatus.Group:
                            order.order_status = "待分享";
                            break;
                        case OrderStatus.Failure:
                            order.order_status = "拼单失败";
                            break;
                        case OrderStatus.Shipment:
                            order.order_status = "待发货";
                            break;
                        case OrderStatus.Receive:
                            order.order_status = "待收货";
                            break;
                        //case OrderStatus.Comment:
                        //    order.order_status = "待评论";
                        //    break;
                        case OrderStatus.Complete:
                            order.order_status = "完成";
                            break;
                        case OrderStatus.GroupComplete:
                            order.order_status = "拼单完成，但未获得商品";
                            break;
                        case OrderStatus.Cancel:
                            order.order_status = "取消";
                            break;
                        default:
                            break;
                    }
                    switch ((PayStatus)order._pay_status)
                    {
                        //case PayStatus.待处理:
                        //    order.pay_status = "待处理";
                        //    break;
                        case PayStatus.已付款:
                            order.pay_status = "已付款";
                            break;
                        case PayStatus.部分退款:
                            order.pay_status = "部分退款";
                            break;
                        case PayStatus.退款:
                            order.pay_status = "退款";
                            break;
                        default:
                            break;
                    }
                    switch ((ShipmentStatus)order._shipment_status)
                    {
                        case ShipmentStatus.未发货:
                            order.shipment_status = "未发货";
                            break;
                        case ShipmentStatus.已发货:
                            order.shipment_status = "已发货";
                            break;
                            //case ShipmentStatus.已收货:
                            //    order.shipment_status = "已交货";
                            //    break;
                    }

                }


                result.code = 1;
                result.data = order;

            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.msg = ex.ToString();
                result.code = 2;
            }
            return result;
        }

        //导出订单
        public Response<string> ExportOrders(string receiver_name, string receiver_mobile, string shop_name, string order_no, string start_date, string end_date, int order_status, int pay_status, int shipment_status, int pay_type, string user_no, int shop_id = -1)
        {
            Response<string> result = new Response<string>();
            result.code = 0;
            try
            {
                var result2 = GetOrders(receiver_name, receiver_mobile, shop_name, order_no, start_date, end_date, order_status, pay_status, shipment_status, pay_type, user_no, 1, 10000, shop_id);

                if (result2.code != 1)
                {
                    result.msg = result2.msg;
                    return result;
                }

                //建立空白工作簿
                IWorkbook workbook = new HSSFWorkbook();
                //在工作簿中：建立空白工作表
                ISheet sheet = workbook.CreateSheet();

                #region 列头及样式
                // 2.设置单元格抬头
                // key：实体对象属性名称，可通过反射获取值
                // value：Excel列的名称
                Dictionary<string, string> cellheader = new Dictionary<string, string> {
                    { "order_no", "订单号" },
                    { "order_status","订单状态"},
                    { "user_id","用户编号"},
                    { "shop_name", "店铺" },
                    { "company_name", "所属商家" },
                    { "order_amout", "订单总金额" },
                    { "add_time", "添加时间" },
                    { "reciver_name", "收件人" },
                    { "reciver_mobile", "收件电话" },
                    { "reciver_area", "配送区域" },
                };
                IRow row = sheet.CreateRow(0);
                List<string> keys = cellheader.Keys.ToList();
                for (int i = 0; i < keys.Count; i++)
                {
                    // 列名为Key的值
                    row.CreateCell(i).SetCellValue(cellheader[keys[i]]);
                }
                #endregion

                #region  样式
                ICellStyle style = workbook.CreateCellStyle();
                //设置单元格的样式：水平对齐居中
                style.Alignment = HorizontalAlignment.Center;
                style.VerticalAlignment = VerticalAlignment.Center;
                //新建一个字体样式对象
                IFont font = workbook.CreateFont();
                //使用SetFont方法将字体样式添加到单元格样式中 
                style.SetFont(font);
                #endregion

                #region 设置单元格数据
                int rowIndex = 1;
                var modelist = result2.data.ToList();
                foreach (var item in modelist)
                {
                    //在工作表中：建立行，参数为行号，从0计
                    IRow row1 = sheet.CreateRow(rowIndex);
                    //在行中：建立单元格，参数为列号，从0计
                    ICell cell = row1.CreateCell(0);
                    cell.SetCellValue(item.order_no);
                    cell.CellStyle = style;

                    ICell cell1 = row1.CreateCell(1);
                    cell1.SetCellValue(item.order_status);
                    cell1.CellStyle = style;

                    ICell cell2 = row1.CreateCell(2);
                    cell2.SetCellValue(item.user_id);
                    cell2.CellStyle = style;

                    ICell cell3 = row1.CreateCell(3);
                    cell3.SetCellValue(item.shop_name);
                    cell3.CellStyle = style;

                    ICell cell4 = row1.CreateCell(4);
                    cell4.SetCellValue(item.company_name);
                    cell4.CellStyle = style;

                    ICell cell5 = row1.CreateCell(5);
                    cell5.SetCellValue(item.amount.ToString("#0.00"));
                    cell5.CellStyle = style;

                    ICell cell6 = row1.CreateCell(6);
                    cell6.SetCellValue(item.add_time.ToString());
                    cell6.CellStyle = style;

                    ICell cell7 = row1.CreateCell(7);
                    cell7.SetCellValue(item.receiver_name);
                    cell7.CellStyle = style;

                    ICell cell8 = row1.CreateCell(8);
                    cell8.SetCellValue(item.receiver_mobile);
                    cell8.CellStyle = style;

                    ICell cell9 = row1.CreateCell(9);
                    cell9.SetCellValue(item.area);
                    cell9.CellStyle = style;

                    rowIndex++;
                }
                #endregion

                #region 设置自适应
                //获取当前列的宽度，然后对比本列的长度，取最大值  
                for (int columnNum = 0; columnNum <= 8; columnNum++)
                {
                    int columnWidth = sheet.GetColumnWidth(columnNum) / 256;
                    for (int rowNum = 1; rowNum <= sheet.LastRowNum; rowNum++)
                    {
                        IRow currentRow;
                        //当前行未被使用过  
                        if (sheet.GetRow(rowNum) == null)
                        {
                            currentRow = sheet.CreateRow(rowNum);
                        }
                        else
                        {
                            currentRow = sheet.GetRow(rowNum);
                        }

                        if (currentRow.GetCell(columnNum) != null)
                        {
                            ICell currentCell = currentRow.GetCell(columnNum);
                            int length = Encoding.Default.GetBytes(currentCell.ToString()).Length;
                            if (columnWidth < length)
                            {
                                columnWidth = length;
                            }
                        }
                    }
                    sheet.SetColumnWidth(columnNum, columnWidth * 256);
                }
                #endregion

                string fileName = "订单-" + Utils.GetOrderNumber() + ".xls"; // 文件名称
                string urlPath = "Download/ExcelFiles/" + fileName; // 文件下载的URL地址，供给前台下载
                // 创建日志文件夹
                string filePath = CommonHelper.GetRootPath + @"Download\ExcelFiles\";

                //string filePath = Current.Server.MapPath("\\" + urlPath); // 文件路径
                // 1.检测是否存在文件夹，若不存在就建立个文件夹
                string directoryName = Path.GetDirectoryName(filePath);
                if (!Directory.Exists(directoryName))
                {
                    Directory.CreateDirectory(directoryName);
                }
                // 4.生成文件
                using (FileStream file = new FileStream(filePath + fileName, FileMode.Create))
                {
                    workbook.Write(file);
                }

                result.code = 1;
                result.data = "/" + urlPath;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.code = 2;
            }

            return result;
        }

        #endregion

        #region 合体免单
        public Response<IPagedList<GetOrdeFreeGroupsOutput>> GetOrderFreeGroups(string group_no, string order_no, string start_date, string end_date, int group_status, int page_index = 1, int page_size = 20, int shop_id = -1)
        {
            Response<IPagedList<GetOrdeFreeGroupsOutput>> result = new Response<IPagedList<GetOrdeFreeGroupsOutput>>();
            try
            {
                //var date = DateTime.Now.AddMonths(-1);
                var source = db.gw_order_groups
                    .Include(o => o.gw_order_group_user)
                    .Include(o => o.gw_goods)
                    .Include(o => o.gw_order)
                    .Include(o => o.gw_goods.gw_goods_picture)
                    .Where(g => g.group_type == 2)
                    .Select(item => new GetOrdeFreeGroupsOutput
                    {
                        group_id = item.id,
                        group_no = item.group_no,
                        expire_time = item.expire_time,
                        add_time = item.add_time,
                        _group_status = item.status,
                        require_num = item.require_num,
                        shop_id = item.gw_goods.shop_id,
                        goods_name = item.gw_goods.name,
                        goods_picture_url = item.gw_goods.gw_goods_picture.FirstOrDefault().url,
                        user_num = item.gw_order_group_user.Count - 1,
                        order_no = item.gw_order.FirstOrDefault().order_no,
                    });

                if (shop_id > -1)
                {
                    source = source.Where(s => s.shop_id == shop_id);
                }

                if (!string.IsNullOrWhiteSpace(group_no))
                {
                    source = source.Where(s => s.group_no == group_no);
                }
                if (!string.IsNullOrWhiteSpace(order_no))
                {
                    source = source.Where(s => s.order_no == order_no);
                }
                if (group_status != (int)GroupStatus.All)
                {
                    source = source.Where(s => s._group_status == group_status);
                }
                if (!string.IsNullOrWhiteSpace(start_date))
                {
                    DateTime start;
                    if (DateTime.TryParse(start_date, out start))
                        source = source.Where(s => s.add_time > start);
                }
                if (!string.IsNullOrWhiteSpace(end_date))
                {
                    DateTime end;
                    if (DateTime.TryParse(end_date, out end))
                        source = source.Where(s => s.add_time <= end);
                }
                source = source.OrderByDescending(s => s.add_time);

                var pagelist = new PagedList<GetOrdeFreeGroupsOutput>(source, page_index, page_size);
                foreach (var item in pagelist)
                {
                    switch ((GroupStatus)item._group_status)
                    {
                        case GroupStatus.Process:
                            item.group_status = "拼单中";
                            break;
                        case GroupStatus.Succeed:
                            item.group_status = "拼单成功";
                            break;
                        case GroupStatus.Failure:
                            item.group_status = "拼单失败";
                            break;
                        case GroupStatus.Cancel:
                            item.group_status = "拼单取消";
                            break;
                    }
                }

                result.code = 1;
                result.data = pagelist;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.msg = ex.ToString();
                result.code = 2;
            }
            return result;
        }

        public async Task<Response<GetOrderFreeGroupOutput>> GetOrderFreeGroup(int group_id, int shop_id = 0)
        {
            Response<GetOrderFreeGroupOutput> result = new Response<GetOrderFreeGroupOutput>();
            try
            {
                var group = await db.gw_order_groups
                    .Include(o => o.gw_order_group_user)
                    .Include(o => o.gw_goods)
                    .Include(o => o.gw_goods.gw_goods_picture)
                    .Where(g => g.id == group_id)
                    .Select(item => new GetOrderFreeGroupOutput
                    {
                        shop_id = item.gw_goods.shop_id,
                        goods_id = item.gw_goods.id,
                        goods_name = item.gw_goods.name,
                        goods_picture_url = item.gw_goods.gw_goods_picture.FirstOrDefault().url,
                        group_id = item.id,
                        group_no = item.group_no,
                        expire_time = item.expire_time,
                        add_time = item.add_time,
                        _group_status = item.status,
                        require_num = item.require_num,
                        user_num = item.gw_order_group_user.Count - 1,
                        group_users = item.gw_order_group_user.Select(u => new OrderGroupUser
                        {
                            acquire_red_packet = u.acquire_red_packet,
                            acquire_time = u.acquire_time,
                            add_time = u.add_time,
                            is_award = u.is_award,
                            is_leader = u.is_leader,
                            _help_status = u.help_status,
                            order_id = u.order_id,
                            order_no = u.gw_order.order_no,
                            user_name = u.gw_user.name,
                        }).ToList()

                    }).FirstOrDefaultAsync();

                if (group == null)
                {
                    result.msg = "没有该拼单";
                    return result;
                }
                if (shop_id != 0)
                {
                    if (group.shop_id != shop_id)
                    {
                        result.msg = "权限不足";
                        return result;
                    }
                }

                if (group != null)
                {
                    switch ((GroupStatus)group._group_status)
                    {
                        case GroupStatus.Process:
                            group.group_status = "拼单中";
                            break;
                        case GroupStatus.Succeed:
                            group.group_status = "拼单成功";
                            break;
                        case GroupStatus.Failure:
                            group.group_status = "拼单失败";
                            break;
                        case GroupStatus.Cancel:
                            group.group_status = "拼单取消";
                            break;
                    }
                    foreach (var item in group.group_users)
                    {
                        if (!item.is_leader)
                        {
                            item.help_status = item._help_status == 2 ? "助力成功" : "助力中";
                        }
                        else
                        {

                        }
                    }
                }
                result.code = 1;
                result.data = group;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.msg = ex.ToString();
                result.code = 2;
            }
            return result;
        }
        #endregion

        #region 拼手气
        public Response<IPagedList<GetOrderGroupsOutput>> GetOrderGroups(string group_no, string start_date, string end_date, int group_status, int page_index = 1, int page_size = 20, int shop_id = -1)
        {
            Response<IPagedList<GetOrderGroupsOutput>> result = new Response<IPagedList<GetOrderGroupsOutput>>();
            try
            {
                //var date = DateTime.Now.AddMonths(-1);
                var source = db.gw_order_groups
                    .Include(o => o.gw_order_group_user)
                    .Include(o => o.gw_goods)
                    .Include(o => o.gw_goods.gw_goods_picture)
                    .Where(g => g.group_type == 1)
                    .Select(item => new GetOrderGroupsOutput
                    {
                        shop_id = item.gw_goods.shop_id,
                        goods_picture_url = item.gw_goods.gw_goods_picture.FirstOrDefault().url,
                        goods_name = item.gw_goods.name,
                        group_id = item.id,
                        group_no = item.group_no,
                        expire_time = item.expire_time,
                        add_time = item.add_time,
                        _group_status = item.status,
                        red_packet = item.red_packet,
                        require_num = item.require_num,
                        user_num = item.gw_order_group_user.Count
                    });

                if (shop_id > -1)
                {
                    source = source.Where(s => s.shop_id == shop_id);
                }
                if (!string.IsNullOrWhiteSpace(group_no))
                {
                    source = source.Where(s => s.group_no == group_no);
                }
                if (group_status != (int)GroupStatus.All)
                {
                    source = source.Where(s => s._group_status == group_status);
                }
                if (!string.IsNullOrWhiteSpace(start_date))
                {
                    DateTime start;
                    if (DateTime.TryParse(start_date, out start))
                        source = source.Where(s => s.add_time > start);
                }
                if (!string.IsNullOrWhiteSpace(end_date))
                {
                    DateTime end;
                    if (DateTime.TryParse(end_date, out end))
                        source = source.Where(s => s.add_time <= end);
                }
                source = source.OrderByDescending(s => s.add_time);

                var pagelist = new PagedList<GetOrderGroupsOutput>(source, page_index, page_size);
                foreach (var item in pagelist)
                {
                    switch ((GroupStatus)item._group_status)
                    {
                        case GroupStatus.Process:
                            item.group_status = "拼单中";
                            break;
                        case GroupStatus.Succeed:
                            item.group_status = "拼单成功";
                            break;
                        case GroupStatus.Failure:
                            item.group_status = "拼单失败";
                            break;
                        case GroupStatus.Cancel:
                            item.group_status = "拼单取消";
                            break;
                    }
                }
                result.code = 1;
                result.data = pagelist;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.msg = ex.ToString();
                result.code = 2;
            }
            return result;
        }

        public async Task<Response<GetOrderGroupOutput>> GetOrderGroup(int group_id, int shop_id = 0)
        {
            Response<GetOrderGroupOutput> result = new Response<GetOrderGroupOutput>();
            try
            {
                var group = await db.gw_order_groups
                    .Include(o => o.gw_order_group_user)
                    .Include(o => o.gw_goods)
                    .Include(o => o.gw_goods.gw_goods_picture)
                    .Where(g => g.id == group_id)
                    .Select(item => new GetOrderGroupOutput
                    {
                        group_id = item.id,
                        group_no = item.group_no,
                        expire_time = item.expire_time,
                        add_time = item.add_time,
                        _group_status = item.status,
                        red_packet = item.red_packet,
                        require_num = item.require_num,
                        user_num = item.gw_order_group_user.Count,
                        shop_id = item.gw_goods.shop_id,
                        goods_id = item.gw_goods.id,
                        goods_name = item.gw_goods.name,
                        goods_picture_url = item.gw_goods.gw_goods_picture.FirstOrDefault().url,
                        group_users = item.gw_order_group_user.Select(u => new OrderGroupUser
                        {
                            acquire_red_packet = u.acquire_red_packet,
                            acquire_time = u.acquire_time,
                            add_time = u.add_time,
                            is_award = u.is_award,
                            is_leader = u.is_leader,
                            order_id = u.order_id,
                            order_no = u.gw_order.order_no,
                            user_name = u.gw_user.name,
                        }).ToList(),
                    }).FirstOrDefaultAsync();

                if (group == null)
                {
                    result.msg = "拼单不存在";
                    return result;
                }

                if (shop_id != 0)
                {
                    if (group.shop_id != shop_id)
                    {
                        result.msg = "权限不足";
                        return result;
                    }
                }

                switch ((GroupStatus)group._group_status)
                {
                    case GroupStatus.Process:
                        group.group_status = "拼单中";
                        break;
                    case GroupStatus.Succeed:
                        group.group_status = "拼单成功";
                        break;
                    case GroupStatus.Failure:
                        group.group_status = "拼单失败";
                        break;
                    case GroupStatus.Cancel:
                        group.group_status = "拼单取消";
                        break;
                }

                result.code = 1;
                result.data = group;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.msg = ex.ToString();
                result.code = 2;
            }
            return result;
        }

        #endregion

        #region 一元购
        public Response<IPagedList<GetOrdeFreeGroupsOutput>> GetOrderWelfareGroups(string group_no, string order_no, string start_date, string end_date, int group_status, int page_index = 1, int page_size = 20, int shop_id = -1)
        {
            Response<IPagedList<GetOrdeFreeGroupsOutput>> result = new Response<IPagedList<GetOrdeFreeGroupsOutput>>();
            try
            {
                //var date = DateTime.Now.AddMonths(-1);
                var source = db.gw_order_groups
                    .Include(o => o.gw_order_group_user)
                    .Include(o => o.gw_goods)
                    .Include(o => o.gw_order)
                    .Include(o => o.gw_goods.gw_goods_picture)
                    .Where(g => g.group_type == (int)GroupType.Welfare)
                    .Select(item => new GetOrdeFreeGroupsOutput
                    {
                        group_id = item.id,
                        group_no = item.group_no,
                        expire_time = item.expire_time,
                        add_time = item.add_time,
                        _group_status = item.status,
                        require_num = item.require_num,
                        shop_id = item.gw_goods.shop_id,
                        goods_name = item.gw_goods.name,
                        goods_picture_url = item.gw_goods.gw_goods_picture.FirstOrDefault().url,
                        user_num = item.gw_order_group_user.Count - 1,
                        order_no = item.gw_order.FirstOrDefault().order_no,
                    });

                if (shop_id > -1)
                {
                    source = source.Where(s => s.shop_id == shop_id);
                }

                if (!string.IsNullOrWhiteSpace(group_no))
                {
                    source = source.Where(s => s.group_no == group_no);
                }
                if (!string.IsNullOrWhiteSpace(order_no))
                {
                    source = source.Where(s => s.order_no == order_no);
                }
                if (group_status != (int)GroupStatus.All)
                {
                    source = source.Where(s => s._group_status == group_status);
                }
                if (!string.IsNullOrWhiteSpace(start_date))
                {
                    DateTime start;
                    if (DateTime.TryParse(start_date, out start))
                        source = source.Where(s => s.add_time > start);
                }
                if (!string.IsNullOrWhiteSpace(end_date))
                {
                    DateTime end;
                    if (DateTime.TryParse(end_date, out end))
                        source = source.Where(s => s.add_time <= end);
                }
                source = source.OrderByDescending(s => s.add_time);

                var pagelist = new PagedList<GetOrdeFreeGroupsOutput>(source, page_index, page_size);
                foreach (var item in pagelist)
                {
                    switch ((GroupStatus)item._group_status)
                    {
                        case GroupStatus.Process:
                            item.group_status = "拼单中";
                            break;
                        case GroupStatus.Succeed:
                            item.group_status = "拼单成功";
                            break;
                        case GroupStatus.Failure:
                            item.group_status = "拼单失败";
                            break;
                        case GroupStatus.Cancel:
                            item.group_status = "拼单取消";
                            break;
                    }
                }

                result.code = 1;
                result.data = pagelist;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.msg = ex.ToString();
                result.code = 2;
            }
            return result;
        }

        public async Task<Response<GetOrderFreeGroupOutput>> GetOrderWelfareGroup(int group_id, int shop_id = 0)
        {
            Response<GetOrderFreeGroupOutput> result = new Response<GetOrderFreeGroupOutput>();
            try
            {
                var group = await db.gw_order_groups
                    .Include(o => o.gw_order_group_user)
                    .Include(o => o.gw_goods)
                    .Include(o => o.gw_goods.gw_goods_picture)
                    .Where(g => g.id == group_id)
                    .Select(item => new GetOrderFreeGroupOutput
                    {
                        shop_id = item.gw_goods.shop_id,
                        goods_id = item.gw_goods.id,
                        goods_name = item.gw_goods.name,
                        goods_picture_url = item.gw_goods.gw_goods_picture.FirstOrDefault().url,
                        group_id = item.id,
                        group_no = item.group_no,
                        expire_time = item.expire_time,
                        add_time = item.add_time,
                        _group_status = item.status,
                        require_num = item.require_num,
                        user_num = item.gw_order_group_user.Count - 1,
                        group_users = item.gw_order_group_user.Select(u => new OrderGroupUser
                        {
                            acquire_red_packet = u.acquire_red_packet,
                            acquire_time = u.acquire_time,
                            add_time = u.add_time,
                            is_award = u.is_award,
                            is_leader = u.is_leader,
                            _help_status = u.help_status,
                            order_id = u.order_id,
                            order_no = u.gw_order.order_no,
                            user_name = u.gw_user.name,
                        }).ToList()

                    }).FirstOrDefaultAsync();

                if (group == null)
                {
                    result.msg = "没有该拼单";
                    return result;
                }
                if (shop_id != 0)
                {
                    if (group.shop_id != shop_id)
                    {
                        result.msg = "权限不足";
                        return result;
                    }
                }

                if (group != null)
                {
                    switch ((GroupStatus)group._group_status)
                    {
                        case GroupStatus.Process:
                            group.group_status = "拼单中";
                            break;
                        case GroupStatus.Succeed:
                            group.group_status = "拼单成功";
                            break;
                        case GroupStatus.Failure:
                            group.group_status = "拼单失败";
                            break;
                        case GroupStatus.Cancel:
                            group.group_status = "拼单取消";
                            break;
                    }
                    foreach (var item in group.group_users)
                    {
                        if (!item.is_leader)
                        {
                            item.help_status = item._help_status == 2 ? "助力成功" : "助力中";
                        }
                        else
                        {

                        }
                    }
                }
                result.code = 1;
                result.data = group;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.msg = ex.ToString();
                result.code = 2;
            }
            return result;
        }
        #endregion

    }
}
